<script language="javascript" type="text/javascript">
	function validateForm() {
	
	var tensp = document.getElementById("tensp");
		tensp.style.backgroundColor="#fff";
		
	var loaisp = document.getElementById("loaisp");
		loaisp.style.backgroundColor="#fff";
		
	var danhmucsp = document.getElementById("danhmucsp");
		danhmucsp.style.backgroundColor="#fff";	
		
		if(tensp.value == ''){
		alert('Vui lòng nhập tên sản phẩm!');
		tensp.focus();
		tensp.style.backgroundColor="#F90";
		return false;
		}

		if(loaisp.value == 0){
		alert('Vui lòng chọn loại!');
		loaisp.focus();
		loaisp.style.backgroundColor="#F90";
		return false;
		}		

		if(danhmucsp.value == 0){
		alert('Vui lòng chọn loại!');
		danhmucsp.focus();
		danhmucsp.style.backgroundColor="#F90";
		return false;
		}
		
	}
</script>
<?php
	$id=$_GET['id'];
	$sql="select * from dm_sanpham where id=".$id;
	$rs=mysql_query($sql);
	$row=mysql_fetch_assoc($rs);

	if(isset($_POST['submit']))
	{
		$masp=$_POST['masp'];				
		$tensp=$_POST['tensp'];		
		$loai=$_POST['loaisp'];
		$danhmuc=$_POST['danhmucsp'];
		$publish=$_POST['publish'];
		$giagoc=$_POST['giagoc'];
		$giaban=$_POST['giaban'];
		$motangan=$_POST['motangan'];
		$motadaydu=$_POST['motadaydu'];
		$ngaydang = time();
		$noibat=$_POST['noibat'];
		$thongsokythuat=$_POST['thongsokythuat'];
		$ordering=$_POST['ordering'];
		$meta_keyword=$_POST['meta_keyword'];
		$meta_description=$_POST['meta_description'];
		$meta_title=$_POST['meta_title'];
		// $alias=$_POST['alias'];
		if( trim($_POST['alias'])=="")
		{
			$alias= HamhaydungLibs::alias($tensp);
		}else{
			$alias= preg_replace("/[^a-zA-Z0-9_\-]+/", "", $_POST['alias']);
		}

		$hinhdaidien=$_FILES['hinhdaidien'];
		
		if(isset($id) && $id >0)
		{		
			if($hinhdaidien['name']!="")
			{
				$urlhinhhinhdaidien=time().'_'.$hinhdaidien['name'];
				move_uploaded_file($hinhdaidien['tmp_name'],"../images/sanpham/hinhdaidien/".$urlhinhhinhdaidien);	
				$hinhdaidien = "   hinhdaidien='$urlhinhhinhdaidien' ,";	
				
				if(file_exists("../images/sanpham/hinhdaidien/".$row['hinhdaidien'])) unlink("../images/sanpham/hinhdaidien/".$row['hinhdaidien']);				
			}else{
				$hinhdaidien = '';
			}


			$sql="update dm_sanpham set 
									   masp='$masp',									 
									   alias='$alias',									 
									   tensp='$tensp',									 
									   loai='$loai',									 
									   danhmuc='$danhmuc',									 
									   publish='$publish',									 
									   giagoc='$giagoc',									 
									   giaban='$giaban',									 
									   motangan='$motangan',									 
									   motadaydu='$motadaydu',									 
									   noibat='$noibat',									 
									   thongsokythuat='$thongsokythuat',									 
									   ordering='$ordering',									 
									   meta_keyword='$meta_keyword',									 
									   meta_description='$meta_description',	
									   $hinhdaidien									   
									   meta_title='$meta_title'									 
									  						  
										where id=".$id;
			// echo $sql;
			mysql_query($sql);			

			$linkhinhsp = '../images/sanpham/'.$id;
			foreach ($_FILES["hinhsanpham"]["error"] as $key => $error) {
				if ($error == UPLOAD_ERR_OK) {
					$tmp_name = $_FILES["hinhsanpham"]["tmp_name"][$key];
					$name = $_FILES["hinhsanpham"]["name"][$key];
					$name= HamhaydungLibs::bodautv($name);
					move_uploaded_file($tmp_name, "$linkhinhsp/$name");
				}
			}
			
			$linksave = 'index.php?action=sanpham_sua&id='.$id;
			echo "<script>alert('Cập nhật sản phẩm thành công');window.location='$linksave';</script>";
			//update
			
		}else{
			
			if($hinhdaidien['name']!="")
			{
				$urlhinhhinhdaidien=time().'_'.$hinhdaidien['name'];
				move_uploaded_file($hinhdaidien['tmp_name'],"../images/sanpham/hinhdaidien/".$urlhinhhinhdaidien);					
			}else{
			$urlhinhhinhdaidien ='';
			}
			
				$sql="INSERT INTO `dm_sanpham` (`masp`, `tensp`, `loai`, `danhmuc`, `publish`, `giagoc`, `giaban`, `motangan`, `motadaydu`, `ngaydang`, `noibat`, 
				`thongsokythuat`, `hinhdaidien`,`ordering`, `meta_keyword`, `meta_description`, `meta_title`, `alias`	)";
				$sql.=" VALUES	('$masp', '$tensp', '$loai', '$danhmuc', '$publish', '$giagoc', '$giaban', '$motangan', '$motadaydu', '$ngaydang', '$noibat', '$thongsokythuat', 
				'$urlhinhhinhdaidien', '$ordering', '$meta_keyword', '$meta_description', '$meta_title', '$alias' )";
			// echo $sql;
			mysql_query($sql);
			$inserid = mysql_insert_id();
			$linkhinhsp = '../images/sanpham/'.$inserid;
			mkdir($linkhinhsp);
			
			foreach ($_FILES["hinhsanpham"]["error"] as $key => $error) {
				if ($error == UPLOAD_ERR_OK) {
					$tmp_name = $_FILES["hinhsanpham"]["tmp_name"][$key];
					$name = $_FILES["hinhsanpham"]["name"][$key];
					$name= HamhaydungLibs::bodautv($name);
					move_uploaded_file($tmp_name, "$linkhinhsp/$name");
				}
			}
			
			echo'<script>alert("Thêm sản phẩm thành công");window.location="?action=sanpham";</script>';

		}
		
	}
?>

<!-- Container -->
<div id="container">
	<div class="shell">

		<!-- Main -->
		<div id="main">
			<div class="cl">&nbsp;</div>
			
			<!-- Content -->
			<div id="content">
				<!-- Box -->
				<div class="box">
					<!-- Box Head -->
					<div class="box-head">
						<h2>Thêm sản phẩm</h2>
					</div>
					<!-- End Box Head -->
					
					<form action="#" id="frmcontent" method="post" enctype="multipart/form-data" onSubmit="return validateForm();">
						
						<!-- Form -->
						<div class="form">
								<p>
									<label>Tên sản phẩm<span> (*)</span></label>
									<input type="text" name="tensp" id="tensp" value="<?php echo $row['tensp'] ?>" class="field size1" />
								</p>

								<p>
									<label>Alias</label>
									<input type="text" name="alias" id="alias" value="<?php echo $row['alias'] ?>" class="field size1" />
								</p>
					
								<p>
									<label>Mô tả ngắn</label>
									<textarea id="motangan" name="motangan" class="field size1" rows="7" cols="30"><?php echo $row['motangan'] ?></textarea>
								</p>	
								
								<p>
									<label>Mô tả đầy đủ</label>
									<textarea id="motadaydu" name="motadaydu" class="field size1" rows="7" cols="30"><?php echo $row['motadaydu'] ?></textarea>
								</p>
								
								<p>
									<label>Thông số kỹ thuật</label>
									<textarea id="thongsokythuat" name="thongsokythuat" class="field size1" rows="7" cols="30"><?php echo $row['thongsokythuat'] ?></textarea>
								</p>
								
								
								<p>
									<label>Hình đại diện</label>
									<input id='logo' name='hinhdaidien' type='file' />	
									
									<?php
									$filename = '../images/sanpham/hinhdaidien/'.$row['hinhdaidien'];
									// $filename1 ='../images/hinhdaidien/'.$row['hinhdaidien'];
									if (file_exists($filename)) 
									{
										echo "<img width='100px' height='100px' src=\"$filename\" />";
										echo "<br/>( chọn hình đại diện khác thì hình này sẽ bị xóa và thay thế bằng hình mới )";
										
									}			
									?>
								</p>
							
								<p>
									<label>Hình sản phẩm</label>
										Hình 1: <input id='logo' name='hinhsanpham[]' type='file'  />	<br/>
										Hình 2: <input id='logo' name='hinhsanpham[]' type='file'  />	<br/>
										Hình 3: <input id='logo' name='hinhsanpham[]' type='file'  />	<br/>
										Hình 4: <input id='logo' name='hinhsanpham[]' type='file'  />	<br/>
										Hình 5: <input id='logo' name='hinhsanpham[]' type='file'  />	<br/>
										
										<?php
										if(isset($row['id']))
										{
											$dirname = "../images/sanpham/$row[id]"; //Thư mục của bạn
											$dir = opendir($dirname);

											$arrfile ="";
											while(false != ($file = readdir($dir)))
											{
												if(($file != ".") and ($file != ".."))
												{
													$tyle= explode(".", $file);
													$kieu = strtolower($tyle[1]);
													if($kieu == 'jpg' || $kieu == 'png' || $kieu == 'gif')
													{
														// echo("$file <br />");
														// $arrfile .= ",('".$file."')";
														echo "<img src='$dirname/$file' width='80px' height='70px'/>";
														echo "<a href='index.php?action=sanpham_xoahinh&id=$row[id]&img=$file'>xóa</a> &nbsp &nbsp &nbsp";
													
													}
												
												}
											}
										}
										// echo $arrfile;
										?>
								</p>
						</div>
						
						
										
				</div>
				<!-- End Box -->

			</div>
			<!-- End Content -->
			
			<!-- Sidebar -->
			<div id="sidebar">
				
				<!-- Box -->
				<div class="box">
					
					<!-- Box Head -->
					<div class="box-head">
						<h2>Chức năng</h2>
					</div>
					<!-- End Box Head-->

					<div class="box-content">
						<div class="buttons">
							<input type="button" onclick="window.location.href='?action=sanpham'" class="button" value="Thoát" />
							<!--<input type="button" onclick="validateForm()" name="submit" class="button" value="Lưu" />-->
							<input type="submit"  name="submit" class="button" value="Lưu" />
						</div>
	
						
						<!-- Sort -->
						<div class="sort">		
						
							<label>Loại sản phẩm:<span> (*)</span></label>
							<select name="loaisp" id="loaisp" class="field" onchange="getDanhmucByLoai(this.value)">
								<option value="0">Tất cả loại</option>
							
								<?php
								$sqlsec="select id, title from dm_sanpham_loai where state=1 ORDER BY title";								
								$querysec=mysql_query($sqlsec);	
								while($rowsec=mysql_fetch_array($querysec))
								{	
									if($row['loai']==$rowsec['id'])
									{
										$selected = "SELECTED";
									}else{
										$selected = "";
									}
									echo "<option  $selected value='$rowsec[id]'>$rowsec[title]</option>";
								}			
								?>
							</select>
							
							<br/>
							<label>Danh mục sản phẩm:<span> (*)</span></label>
							<?php
							if(isset($row['danhmuc']))
							{
								echo '<select name="danhmucsp" id="danhmucsp" class="field">';
								$sqlcat="select id, title from dm_sanpham_danhmuc where state=1 AND loai=$row[loai]";								
								$querycat=mysql_query($sqlcat);	
								while($rowcat=mysql_fetch_array($querycat))
								{
									if($row['danhmuc']==$rowcat['id'])
									{
										$selected = "SELECTED";
									}else{
										$selected = "";
									}
									echo "<option $selected value='$rowcat[id]'>$rowcat[title]</option>";
								}
								echo "</select>";
							}else{
							?>	
							<select name="danhmucsp" class="field" id="danhmucsp">
								<option value="0">Tất cả danh mục</option>
							</select>
							<?php
							}
							?>
							<br/>
							<label>Mã sản phẩm</label>
							<input type="text" name="masp" value="<?php echo $row['masp'] ?>" class="field" />
							
							<br/>
							<label>Giá bán</label>
							<input type="text" name="giaban" value="<?php echo $row['giaban'] ?>" class="field" />
							
							<br/>
							<label>Giá gốc</label>
							<input type="text" name="giagoc" value="<?php echo $row['giagoc'] ?>" class="field" />
							

							<br/>
							<label>Thứ tự</label>
							<input type="text" name="ordering" value="<?php echo $row['ordering'] ?>" class="field" />
							
							<br/>
							<label>Ẩn/hiển</label>
							<div style="margin:16px;  background-color: gainsboro; height: 17px;">
							<?php
							if(!isset($row['publish']))
							{
								$checked0 = "";
								$checked1 = "CHECKED";
							}else{
								if($row['publish']==1)
								{
									$checked0 = "";
									$checked1 = "CHECKED";
								}else{
									$checked0 = "CHECKED";
									$checked1 = "";
								}
							}
							?>
							<span style="margin-right:10px; margin-left: 20px;">Bật</span><INPUT TYPE=radio <?php echo $checked1?>  NAME="publish" VALUE="1">&nbsp &nbsp &nbsp &nbsp &nbsp
							<span style="margin-right:10px">Tắt</span><INPUT TYPE=radio <?php echo $checked0?> NAME="publish" VALUE="0">
							</div>	

							<br/>
							<label>Sản phẩm nổi bật</label>
							<div style="margin:16px;  background-color: gainsboro; height: 17px;">
							<?php
							if(!isset($row['noibat']))
							{
								$checked0 = "";
								$checked1 = "CHECKED";
							}else{
								if($row['noibat']==1)
								{
									$checked0 = "";
									$checked1 = "CHECKED";
								}else{
									$checked0 = "CHECKED";
									$checked1 = "";
								}
							}
							?>
							<span style="margin-right:10px; margin-left: 20px;">Bật</span><INPUT TYPE=radio <?php echo $checked1?>  NAME="noibat" VALUE="1">&nbsp &nbsp &nbsp &nbsp &nbsp
							<span style="margin-right:10px">Tắt</span><INPUT TYPE=radio <?php echo $checked0?> NAME="noibat" VALUE="0">
							</div>	
							
							<label>Keywords</label>
							<textarea cols="30" rows="10" class="field" name="meta_keyword" id="meta_keyword" style="width: 188px; height: 60px;"><?php echo $row['meta_keyword'] ?></textarea>
						
							<label>Description</label>
							<textarea id="meta_description" name="meta_description" class="field" rows="10" cols="30" style="width: 188px; height: 175px;"><?php echo $row['meta_description'] ?></textarea>
							
							<label>Meta title</label>
							<input type="text" name="meta_title" value="<?php echo $row['meta_title'] ?>" class="field" />
						</div>
						<!-- End Sort -->
						
					</div>
				</div>
				<!-- End Box -->
			</div>
			<!-- End Sidebar -->
			</form>
			<div class="cl">&nbsp;</div>			
		</div>
		<!-- Main -->
	</div>
</div>
<!-- End Container -->
<script>
	var editor=CKEDITOR.replace( 'motadaydu' );
	CKFinder.setupCKEditor( editor, '../libs/ckfinder/' ) ;
	
	var editthongsokythuat=CKEDITOR.replace( 'thongsokythuat' );
	CKFinder.setupCKEditor( editthongsokythuat, '../libs/ckfinder/' ) ;

</script>
